package com.Model;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.Model.Database.Database;
import com.UI.RetrieveStudyInfo;
import com.UI.RetriveToDoInfo;

import android.content.*;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;

public class StudentDBModel {
	private Context context;

	/**
	 * Constructor This constructor simply stores the context, which is the
	 * owner of the database connection.
	 * 
	 * @param context
	 *            The calling component (e.g. Activity)
	 */
	public StudentDBModel(Context context) {
		this.context = context;
	}

	/**
	 * This utility method obtains a database connection.
	 * 
	 * @return An active connection to the database
	 */
	SQLiteDatabase openConnection() {
		Database helper = new Database(context);
		return helper.getWritableDatabase();
	}

	/**
	 * This utility method closes the connection to the database
	 */
	public void close() {
		Database helper = new Database(context);
		helper.close();
	}

	/**
	 * This method is used to create a new User Account.
	 * 
	 * @param values
	 *            The User Account details (first name, last name, etc.)
	 */
	
	
	public void addNewAccount(ContentValues values) {
		SQLiteDatabase db = openConnection();

		db.insert("User", null, values);

		db.close();
	}

	
	/**
	 * updateUser method takes in Content values and updates the user table in
	 * the database. For now this method is only used by the preferences.
	 * 
	 * @return just updates the table returns void
	 */

	public void updateUser(ContentValues values) {
		SQLiteDatabase db = openConnection();
		db.update("User", values, null, null);
		db.close();

	}
	
	
	
	
	/**  Author : Mohammed
	 * 	 This method is used to create a new course.
	 * 
	 */
	
	public void addNewCourses(ContentValues courseData) {
		SQLiteDatabase db = openConnection();

		db.insert("Courses", null, courseData);

		db.close();
	}

	
	
	/**  Author : Mohammed
	 *   This method is used to update a specific course
	 * 
	 *
	 */
	public void updateCourses(ContentValues values, String courseNo) {
		SQLiteDatabase db = openConnection();

		db.update("Courses", values, "CourseId=?" , new String[] { courseNo });

		db.close();
	}
	
	
	
	/**  Author : Mohammed
	 * 	 This method is used to delete a course.
	 *  
	 */
	
	public void deleteCourses(String courseID) {

		SQLiteDatabase db = openConnection();

		db.delete("Courses", "CourseId" + "=?", new String[] { courseID });

		db.close();
	}

	


	/** Author : Mohammed
	 * 
	 * This method returns the number of courses in the database.
	 * @return The number of courses currently in the database
	 */
	public int getNumCourses() {
		SQLiteDatabase db = openConnection();

		// execute the query, which counts the contacts
		Cursor cursor = db.query("Courses",
				new String[] { "COUNT(CourseName)" }, null, null, null, null,
				null);

		// obtain the data
		int numCourses = 0;
		if (cursor.moveToFirst()) {
			numCourses = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numCourses;
	}
	
	
    
	/** Author : Mohammed
	 * This method fetches all the courses from the database and return a list that will be
	 * displayed in the listview
	 * */
    
    public List<String> selectCoursesByNo() {
		SQLiteDatabase db = openConnection();

		List<String> list = new ArrayList<String>();
		Cursor cursor = db.query("Courses", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				list.add(cursor.getString(0));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return list;
	}
    
    
	/** Author : Mohammed
	 * This method fetches all the courses from the database and return a list that will be
	 * displayed in the listview
	 * */
    
    public List<String> selectCoursesByTitle() {
		SQLiteDatabase db = openConnection();

		List<String> list = new ArrayList<String>();
		Cursor cursor = db.query("Courses", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				list.add(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return list;
	}
    
    
    
	/** Author : Mohammed 
	 * 
	 * This function fetches information for a specific course and returns a ArrayList with 
	 * all the columns info for a specific Course. It will be then pasted in EditCourse class fields
	 * */
    
    
    public ArrayList<String> getCourseDetails(String courseNo) {
    	
    	SQLiteDatabase db = openConnection();
    	
    	ArrayList courseDetails = new ArrayList();
    	    	
		String [] columns=new String[]{"CourseId","CourseName","Section","Location","Credit","ProfEmail","Website","Day","StartTime","EndTime"};

		int i = 0;
		
		
		Cursor c = db.query("Courses", columns,"CourseId"+"=?", new String[]{courseNo}, null, null, null);
		c.moveToFirst();
		
		while (i<7) {
				courseDetails.add(c.getString(i));
				i++;
			} 
		
		c.close();
		db.close();
    	
    	return courseDetails;
    	
    }
    

	/** Author : Mohammed 
	 * 
	 * This function fetches information for specific course that is displayed 
	 * in a separate course page
	 * */
    
    
	public List<String> displayCourseSchedule() {
		SQLiteDatabase db = openConnection();

		  StringBuilder course = new StringBuilder();
		
	      List<String> list = new ArrayList<String>();
		
		   Cursor cursor=db.query("Courses", null, null, null, null, null, null);
	 	    if (cursor.moveToFirst()) {
		 	    do {
		 	    	list.add("\n\n " + cursor.getString(1) + "\n\n " 
		 	    	+ cursor.getString(7) + "\t\t(" + cursor.getString(8)
					+ " - " + cursor.getString(9) + ")\n"
					+ " Location:  "+ cursor.getString(3) + "\n");
	 	         } while (cursor.moveToNext());
	 	      }
	 	 
	 	    if (cursor != null && !cursor.isClosed()) {
		 	         cursor.close();
		 	      }
		 	      return list;
	}

	
	public StringBuilder displayCourse(String courseNo) {
		
		SQLiteDatabase db = openConnection();
		StringBuilder course = new StringBuilder();
		
		// next 2 lines help to add course grade to ViewCourseActivity 
		List <String> records = getGradeProgress();  		
		String grade = getCourseGrade(records, courseNo);
				      
		   String [] columns=new String[]{"CourseId","CourseName","Section","Location","Credit","ProfEmail","Website","Day","StartTime","EndTime"};
		
		   Cursor cursor=db.query("Courses", columns,"CourseId"+"=?", new String[]{courseNo}, null, null, null);
		   if(  cursor.moveToFirst()) {
		   course.append("\nID: " + cursor.getString(0) + "\nTitle: " + cursor.getString(1)
					+ "\nSection: " + cursor.getString(2) + "\nLocation: "
					+ cursor.getString(3) + "\nCredit: "
					+ cursor.getString(4) + "\nEmail: "
					+ cursor.getString(5) + "\nWebsite: "
					+ cursor.getString(6) + "\nDay : "
					+ cursor.getString(7) + "\nTime -> "
					+ cursor.getString(8) + " - "
					+ cursor.getString(9) + "\n" 
					+ "Course Grade: " + grade);		   
		   }

		cursor.close();
		db.close();
		return course;
	}

	
	
	
	
	/**
	 *  Author : Mohammed
	 *  
	 *  This Method takes a course ID  and returns the class website link for that specific course
	 */
	
	
	public StringBuilder getWebLink(String courseNo){
		
		SQLiteDatabase db = openConnection();
		
		StringBuilder link = new StringBuilder();
		
		String [] columns=new String[]{"Website"};
				
		Cursor c = db.query("Courses", columns,"CourseId"+"=?", new String[]{courseNo}, null, null, null);
		c.moveToFirst();
		
		link.append(c.getString(0));
		
		c.close();
		db.close();
		return link;
		
	}
	
	
	
	/** Author :  Mohammed
	 * 
	 * 
	 */
	
	
	public void addToDo(ContentValues courseData) {
		SQLiteDatabase db = openConnection();

		db.insert("CourseToDo", null, courseData);

		db.close();
	}
	
	
	/**  Author : Mohammed
	 * 	 This method is used to delete a course.
	 *  
	 */
	
	public void deleteToDo(String desc) {

		SQLiteDatabase db = openConnection();

		db.delete("CourseToDo", "Desc" + "=?", new String[] { desc });

		db.close();
	}
	
	
	
	/** Author : Mohammed
	 * This method fetches all the courses from the database and return a list that will be
	 * displayed in the listview
	 * */
    
    public List<RetriveToDoInfo> selectToDo() {
		SQLiteDatabase db = openConnection();

		List<RetriveToDoInfo> list = new ArrayList<RetriveToDoInfo>();
		Cursor cursor = db.query("CourseToDo", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				list.add(new RetriveToDoInfo(cursor.getString(1),cursor.getString(0),cursor.getString(3), cursor.getString(4)));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return list;
	}
	
	
	/** Author : Mohammed
	 * This method fetches all the courses from the database and return a list that will be
	 * displayed in the listview
	 * */
    
    public List<String> selectToDoDesc() {
		SQLiteDatabase db = openConnection();

		List<String> list = new ArrayList<String>();
		Cursor cursor = db.query("CourseToDo", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				list.add(cursor.getString(2));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return list;
	}	
	
    
    
    
	/**Author: Anshul
	 * For the preferences screen This method finds out all the details about
	 * the user stored in the database
	 * */
	public ContentValues getUserDetails() {
		SQLiteDatabase db = openConnection();
		ContentValues values = new ContentValues();
		// execute the query, which counts the contacts
		Cursor cursor = db.query("User", null, null, null, null,
				null, null);

		// obtain the data
		// For the bases of this project we will be assume that there is only
		// one user ever
		if (cursor.moveToFirst()) {
			values.put("FirstName", cursor.getString(0));
			values.put("LastName", cursor.getString(1));
			values.put("Major", cursor.getString(2));
			values.put("University", cursor.getString(3));
		}

		cursor.close();
		db.close();
		return values;
	}

	/**
	 * For the preferences screen This method finds out all the details about
	 * the user stored in the database
	 * */
	public ContentValues getCourseById() {
		SQLiteDatabase db = openConnection();
		ContentValues values = new ContentValues();
		// execute the query, which counts the contacts
		Cursor cursor = db.query("Courses", null, null, null, null,
				null, null);

		// obtain the data
		// For the bases of this project we will be assume that there is only
		// one user ever
		if (cursor.moveToFirst()) {
			values.put("CourseId", cursor.getString(0));
		}

		cursor.close();
		db.close();
		return values;
	}
	
	/**Author: Anshul
	 * This method adds the preferences for the user in the preferences table.
	 * For example if he/wants the app to start with a course according to time
	 * or should the app keep a track of the courses.
	 * for the preferences screen , by default all the user choices will be 
	 * selected as YES. These are hardcoded default values which the user 
	 * can change whenever he/she wants
	 * */
	public void addPreferences() {
		SQLiteDatabase db = openConnection();
		ContentValues values = new ContentValues();
		values.put("startapp", "YES");
		values.put("trackgrades", "YES");
		db.insert("Preferences", null, values);

		db.close();
	}

	/**Author: Anshul
	 * This method updates the preferences of the user.
	 * 
	 * @return updating values in the database
	 */

	public void updatePreferences(ContentValues values) {
		SQLiteDatabase db = openConnection();

		db.update("Preferences", values, null, null);
		db.close();
	}

	/**Author: Anshul
	 * For getting the preferences. Used by the preferences screen.
	 * @return ContentValues representing the preferences.
	 * */
	public ContentValues getPreferences() {
		ContentValues values = new ContentValues();
		SQLiteDatabase db = openConnection();
		Cursor cursor = db.query("Preferences", null, null, null, null,
				null, null);

		if (cursor.moveToFirst()) {
			values.put("startapp", cursor.getString(0));
			values.put("trackgrades", cursor.getString(1));
		}
		cursor.close();
		db.close();
		return values;
	}


	/**
	 * This method returns the number of users in the database.
	 * 
	 * @return The number of users currently in the database
	 */
	public int getNumUsers() {
		SQLiteDatabase db = openConnection();

		// execute the query, which counts the contacts
		Cursor cursor = db.query("User", new String[] { "COUNT(FirstName)" },
				null, null, null, null, null);

		// obtain the data
		int numUsers = 0;
		if (cursor.moveToFirst()) {
			numUsers = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numUsers;
	}

	/**
	 * This method is used to add a new ClassEvent.
	 * 
	 * @param values
	 *            The ClassEvent details (course number, name, weight, etc.)
	 */
	public void addNewClassEvent(ContentValues values) {
		SQLiteDatabase db = openConnection();

		db.insert("ClassEvent", null, values);
		db.close();
	}

	/**
	 * This method returns the number of class events in the database.
	 * 
	 * @return The number of class events currently in the database
	 */
	public int getNumClassEvents() {
		SQLiteDatabase db = openConnection();

		// execute the query, which counts the assignments
		Cursor cursor = db.rawQuery("SELECT COUNT(*) " +
									"FROM ClassEvent;", null);

		// obtain the data
		int numClassEvents = 0;
		if (cursor.moveToFirst()) {
			numClassEvents = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numClassEvents;
	}
	
	/**
	 * This function will delete the corresponding Class Event for the given params
	 * @param eventName : the event name
	 * @param courseID : the courseID for the course the class event belongs to
	 */
	public void deleteClassEvent(String comboID) {

		SQLiteDatabase db = openConnection();

		db.delete("ClassEvent", "EventCourseComboId = ?", new String[] {comboID });

		db.close();
	}
	
	/** Author : Steve
	 * This method fetches all the class events from the database and returns a list that will be
	 * displayed in ClassEventList
	 * */
    
    public List<String> selectClassEvents(String courseID) {
		SQLiteDatabase db = openConnection();

		List<String> classEventList = new ArrayList<String>();
		Cursor cursor = db.query("ClassEvent", null, "CourseId"+"=?", new String[] { courseID }, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				classEventList.add(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return classEventList;
	}
    
	/** Author : Steve 
	 * 
	 * This function fetches information for a specific class event that is displayed 
	 * on a separate class event page
	 * */
      
	public StringBuilder displayClassEvent(String comboID) {
		SQLiteDatabase db = openConnection();

		StringBuilder classEvent = new StringBuilder();
		
		   String [] columns=new String[]{"EventName", "CourseId", "EventType", "EventWeight", "DueDate", "MarkReceived", "OutOf"};

		
		   Cursor cursor=db.query("ClassEvent", columns, "EventCourseComboId=?", new String[] {comboID}, null, null, null);
		   cursor.moveToFirst();
		   classEvent.append("\n Event Name: " + cursor.getString(0) 
					+ "\n Course: " + cursor.getString(1) + "\n EventType: "
					+ cursor.getString(2) + "\n Weight: "
					+ cursor.getString(3) + "\n Due Date: "
					+ cursor.getString(4) + "\n Mark Received: "
					+ cursor.getString(5) + " / "
					+ cursor.getString(6) + "\n");

		cursor.close();
		db.close();
		return classEvent;
	}
	
	/**
	 * This function will update the details for a specific class event
	 * @param values : the class event details
	 * @param comboID : the ID of the class event
	 */
	public void updateClassEvent(ContentValues values, String comboID) {
		SQLiteDatabase db = openConnection();

		db.update("ClassEvent", values, "EventCourseComboId=?" , new String[] { comboID });

		db.close();
	}
	
	/** Author : Steve
	 * 
	 * This function fetches information for a specific class event.
	 * @param comboID : the ID of the class event
	 * @return eventDetails : The class event details
	 * */
    
    
    public ArrayList getClassEventDetails(String comboID) {
    	
    	SQLiteDatabase db = openConnection();
    	
    	ArrayList eventDetails = new ArrayList();
    	    	
		String [] columns=new String[]{"EventCourseComboId","EventName","CourseId","EventType","MarkReceived","OutOf","EventWeight","DueDate"};

		Cursor cursor = db.query("ClassEvent", columns,"EventCourseComboId=?", new String[]{comboID}, null, null, null);
		cursor.moveToFirst();
		int index = 0;
		
		while(index < 8){
			eventDetails.add(cursor.getString(index));
			index++;
		}
		cursor.close();
		db.close();
    	
    	return eventDetails;
    	
    }

	/**
	 * This method is used to add new Faculty Hours.
	 * 
	 * @param values
	 *            The Faculty Hours details (CourseId, Faculty name, Location, etc.)
	 */
	public void addNewFacultyHours(ContentValues values) {
		SQLiteDatabase db = openConnection();

		db.insert("Faculty", null, values);
		db.close();
	}
	
	/**
	 * This method returns the number of faculty in the database.
	 * 
	 * @return The number of class events currently in the database
	 */
	public int getNumFaculty() {
		SQLiteDatabase db = openConnection();

		// execute the query, which counts the assignments
		Cursor cursor = db.rawQuery("SELECT COUNT(*) " +
									"FROM Faculty;", null);

		// obtain the data
		int numFaculty = 0;
		if (cursor.moveToFirst()) {
			numFaculty = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numFaculty;
	}
	
	/**
	 * This function will delete the corresponding Faculty entry for the given params
	 * @param comboID : the comboID for the course the Faculty corresponds to
	 */
	public void deleteFaculty(String comboID) {

		SQLiteDatabase db = openConnection();

		db.delete("Faculty", "FacCourseComboId = ?", new String[] {comboID });

		db.close();
	}
	
	/** Author : Steve
	 * This method fetches all the Faculty for a given course from the database 
	 * and returns a list that will be displayed in FacultyHoursList
	 * */
    
    public List<String> selectFacultyHours(String courseID) {
		SQLiteDatabase db = openConnection();

		List<String> facHoursList = new ArrayList<String>();
		Cursor cursor = db.query("Faculty", null, "CourseId"+"=?", new String[] { courseID }, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				facHoursList.add(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return facHoursList;
	}
    
	/** Author : Steve 
	 * 
	 * This function fetches information for specific faculty hours that are displayed 
	 * on a separate faculty hours page
	 * */
      
	public StringBuilder displayFacultyHours(String comboID) {
		SQLiteDatabase db = openConnection();

		StringBuilder facHourInfo = new StringBuilder();
		
		   String [] columns=new String[]{"FacName", "FacType", "FacLocation", "FacHours", "CourseId"};

		
		   Cursor cursor=db.query("Faculty", columns, "FacCourseComboId=?", new String[] {comboID}, null, null, null);
		   cursor.moveToFirst();
		   facHourInfo.append("\n Faculty Name: " + cursor.getString(0) 
					+ "\n Position: " + cursor.getString(1) + "\n Location: "
					+ cursor.getString(2) + "\n Hours: "
					+ cursor.getString(3) + "\n Course: "
					+ cursor.getString(4) + "\n");

		cursor.close();
		db.close();
		return facHourInfo;
	}
	
	/**
	 * This function will update the details for a specific faculty
	 * @param values : the faculty details
	 * @param comboID : the ID of the faculty
	 */
	public void updateFacultyHours(ContentValues values, String comboID) {
		SQLiteDatabase db = openConnection();

		db.update("Faculty", values, "FacCourseComboId=?" , new String[] { comboID });

		db.close();
	}
	
	/** Author : Steve
	 * 
	 * This function fetches information for specific faculty hours.
	 * @param comboID : the ID of the faculty
	 * @return facDetails : The faculty details
	 * */
    
    
    public ArrayList getFacultyHoursDetails(String comboID) {
    	
    	SQLiteDatabase db = openConnection();
    	
    	ArrayList facultyDetails = new ArrayList();
    	    	
		String [] columns=new String[]{"FacCourseComboId","FacName","FacType","FacLocation","FacHours","CourseId"};

		Cursor cursor = db.query("Faculty", columns,"FacCourseComboId=?", new String[]{comboID}, null, null, null);
		cursor.moveToFirst();
		int index = 0;
		
		while(index < 6){
			facultyDetails.add(cursor.getString(index));
			index++;
		}
		cursor.close();
		db.close();
    	
    	return facultyDetails;
    	
    }

	/**@author Anshul
	 * This method is used to delete all users from the User table
	 */
	public void deleteAllUsers() {
		SQLiteDatabase db = openConnection();

		// execute the query, which deletes the users
		db.delete("User", null, null);
		db.close();

	}

	/**
	 * This method is used to add a new StudentWebmail.
	 * 
	 * @param values
	 *            The StudentWebmail address
	 */
	public void addNewStudentWebmail(ContentValues values) {
		SQLiteDatabase db = openConnection();

		db.insert("StudentWebmail", null, values);
		db.close();
	}

	/**
	 * This method returns the number of StudentWebmails in the database.
	 * 
	 * @return The number of StudentWebmails currently in the database
	 */
	public int getNumWebmails() {
		SQLiteDatabase db = openConnection();
		// execute the query, which counts the projects
		Cursor cursor = db.query("StudentWebmail",
				new String[] { "WebmailAddress" }, null, null, null,
				null, null);

		// obtain the data
		int numWebmails = 0;
		String webmail;
		if (cursor.moveToFirst()) {
			webmail = cursor.getString(0);
			if(webmail.compareTo("") == 0){
				numWebmails = 0;
			}
			else{
				numWebmails++;
			}
		}
		cursor.close();
		db.close();

		return numWebmails;
	}

	/**
	 * getWebmailUrl gets the url for the webmail added in by the user.
	 * 
	 * @return the webmail url.
	 * */
	public String getWebmailUrl() {
		SQLiteDatabase db = openConnection();

		// execute the query, which selects the webmail address from the table
		Cursor cursor = db.query("StudentWebmail", null, null, null, null,
				null, null);

		// obtain the data
		String webmailUrl = null;
		if (cursor.moveToFirst()) {
			webmailUrl = cursor.getString(0);
		}
		cursor.close();
		db.close();

		return webmailUrl;
	}
	
	/**
	 * This function will delete all entries in the StudentWebmail table
	 */
	public void deleteAllWebmails() {
		SQLiteDatabase db = openConnection();

		// execute the query, which deletes the users
		db.delete("StudentWebmail", null, null);
		db.close();

	}

	/**
	 * This method returns the number of TAGA in the Faculty Table.
	 * 
	 * @return The number of TAGA currently in the database
	 */
	public int getNumTAGA() {
		SQLiteDatabase db = openConnection();

		// execute the query, which counts the assignments
		Cursor cursor = db.rawQuery(
				"SELECT COUNT(*) FROM Faculty WHERE FacType = 'TA/GA';", null);

		// obtain the data
		int numTAGA = 0;
		if (cursor.moveToFirst()) {
			numTAGA = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numTAGA;
	}

	/**
	 * This method returns the number of Profs in the Faculty Table.
	 * 
	 * @return The number of Profs currently in the database
	 */
	public int getNumProf() {
		SQLiteDatabase db = openConnection();

		// execute the query, which counts the assignments
		Cursor cursor = db.rawQuery(
				"SELECT COUNT(*) FROM Faculty WHERE FacType = 'Prof';", null);

		// obtain the data
		int numProf = 0;
		if (cursor.moveToFirst()) {
			numProf = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numProf;
	}

	/**
	 * This method will retrieve the current grade percentage 
	 * for the course and display it in the Grades page
    */

	public List<String> getGradeProgress() {
		
		SQLiteDatabase db = openConnection();
		List<String> list = new ArrayList<String>();
		List<String> courseList = new ArrayList<String>();
		List<String> tempList = new ArrayList<String>();
		ContentValues args = new ContentValues();
		float markReceived,outOf,weight;
		float percentage;
		String courseId,eventName,formatPercent;
		DecimalFormat df = new DecimalFormat("#.##");
		
		//this cursor will update the classevent with the correct percentage
		Cursor cursor = db.query("ClassEvent", null, null, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			do {				
				courseId = cursor.getString(2);
				eventName = cursor.getString(1);				
				outOf = cursor.getFloat(5);
				markReceived = cursor.getFloat(4);
				weight = cursor.getFloat(6);	
							
				percentage =  (float)markReceived / (float)outOf * (float)weight;								
					
				formatPercent = df.format(percentage);
			
				args.put("Percentage", formatPercent);	
				
			    db.update("ClassEvent", args,"CourseId=? AND eventName=?"   ,new String[] {courseId,eventName}) ;
			    								
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		
		//this cursor will add the total percentage for each course
		Cursor cursor2 = db.query("ClassEvent",
				new String[] { "courseId, SUM(percentage), SUM(eventweight)" }, "Outof > 0", null, "courseId", null,
				null);
		if (cursor2.moveToFirst()) {
			do {	
				tempList.add(cursor2.getString(0));  // add just course number
			    list.add(cursor2.getString(0) + ":" + "\t\t" + cursor2.getString(1) + "/" + cursor2.getString(2)+ "%");
			} while (cursor2.moveToNext());
		}
		
		// get a list of courses where no mark has been added for a class event
		courseList = selectCoursesByNo();
		
		for (String courseNo : courseList) {   
			if (tempList.contains(courseNo)) {      
			}   
			else {     
				list.add(courseNo + ":" + "\t\t" + 0 + "/" + 0+ "%");  // add course where no mark added yet
			} 
		}
			
		db.close();
        cursor2.close();
               
		return list;

	}
	
	/**
	 * This method will get single course grade to show in ViewCourseActivity
	 *
	 */
	public String getCourseGrade(List<String> records, String courseNo) {	
		
		String sResult[];
		
		for (String grade : records) {   
			if (grade.startsWith(courseNo)) { 				
				sResult = grade.split(":");
        		grade = sResult[1];	
        		grade = grade.substring(2);
				return grade;
			}   
		}
		
		return null;
	}

	/** Author: Sugat Mahanti
	 * This method add a new study contact information
	 *
	 */
	public void addNewStudyInfo(ContentValues values){
		SQLiteDatabase db = openConnection();

		db.insert("StudyInfo", null, values);
		db.close();
	}
	
	/**  Author: Sugat Mahanti
	 * This method will get the number of study contact information saved.
	 */
	
	public int getNumStudyInfo() {
		
		SQLiteDatabase db = openConnection();		// execute the query, which counts the Study Info
		Cursor cursor = db.query("StudyInfo", new String[] {"COUNT(GroupName)"}, null, null, null, null, null);
		
		// obtain the data
		int numStudyInfo = 0;
		if (cursor.moveToFirst()) {
			numStudyInfo  = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numStudyInfo;
	}
	
	public List<String> getStudyInfo() {
		SQLiteDatabase db = openConnection();
		List<String> list = new ArrayList<String>();
		Cursor cursor = db.query("StudyInfo", null, null, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			do {
				
				list.add(cursor.getString(0) + "\t" + cursor.getString(1)
				+ "\t\t" + cursor.getString(2) + "/" + cursor.getString(3));					
								
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();

		return list;

	}
	
	public StringBuilder displayStudyInfo(String courseNo) {
		SQLiteDatabase db = openConnection();

		StringBuilder studyinfo = new StringBuilder();
		
		   String [] columns=new String[]{"CourseId","GroupName","GroupTime","GroupNotes"};

		
		   Cursor cursor=db.query("StudyInfo", columns,"CourseId"+"=?", new String[]{courseNo}, null, null, null);
		  
		   // added if statement here to eliminate force close when no study info found 
		   if(cursor.moveToFirst()){
			   
			   studyinfo.append("Course Id " + cursor.getString(0) + "\n Group Members Name " + cursor.getString(1)
						+ "\n Group Meeting Time " + cursor.getString(2) + "\n Group Notes "
						+ cursor.getString(3)+ "\n");			   
		   }

		cursor.close();
		db.close();
		return studyinfo;
	}
	
	/**  Author: Sugat Mahanti
	 * This will delete Study Group Information for the course
	 */
	
	
	public void deleteStudyInfo(String groupname) {

		SQLiteDatabase db = openConnection();

		db.delete("StudyInfo", "GroupName = ?", new String[] { groupname});

		db.close();
	}
	/**  Author: Sugat Mahanti
	 * This will select and add Courses,Group Members Name, Meeting Time to class Retrieve Study Info
	 *  
	 */
	public List<RetrieveStudyInfo> selectStudyInfo() {
		SQLiteDatabase db = openConnection();

		List<RetrieveStudyInfo> list = new ArrayList<RetrieveStudyInfo>();
		Cursor cursor = db.query("StudyInfo", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				list.add(new RetrieveStudyInfo(cursor.getString(1),cursor.getString(0),cursor.getString(2)));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return list;
	}
	
	
	/**  Author: Sugat Mahanti
	 * This will retrieve the Study Information
	 */
	public List<String> selectStudyInfoName() {
		SQLiteDatabase db = openConnection();

		List<String> list = new ArrayList<String>();
		Cursor cursor = db.query("StudyInfo", null, null, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				list.add(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor.close();
		db.close();
		return list;
	}
	/**
	 * Author Sugat Mahanti
	 * It returns the number of To Do data/
	 */
	
	public int  getNumToDo(){
		SQLiteDatabase db = openConnection();		// execute the query, which counts the Study Info
		Cursor cursor = db.query("CourseToDo", new String[] {"COUNT(Desc)"}, null, null, null, null, null);
		
		// obtain the data
		int numToDo = 0;
		if (cursor.moveToFirst()) {
			numToDo  = cursor.getInt(0);
		}
		cursor.close();
		db.close();
		return numToDo;
	}
	
	
	
	
	/**Author: Sugat Mahanti
	 * Updates the Study Contact Information 
	 * @param values
	 * @param cid
	 */
	
	public void updateStudyInfo(ContentValues values, String GroupName) {
		SQLiteDatabase db = openConnection();

		db.update("StudyInfo", values, "GroupName = ?" , new String[] { GroupName });

		db.close();
	}
	
	
	
	
	
	
	
	/**
	 * Author: Sugat Mahanti
	 * It returns the details for Study Group Contact Information currently exisiting in the database
	 * @param cid - CourseID
	 * @return StudyInfo
	 */
	
	
public ArrayList getStudyInfoDetails(String GroupName) {
    	
    	SQLiteDatabase db = openConnection();
    	
    	ArrayList StudyInfo = new ArrayList();
    	    	
		String [] columns=new String[]{"CourseId","GroupName","GroupTime","GroupNotes"};

		Cursor cursor=db.query("StudyInfo", columns,"GroupName = ?", new String[]{GroupName}, null, null, null);
		cursor.moveToFirst();
		int index = 0;
		
		while(index < 4){
			StudyInfo.add(cursor.getString(index));
			index++;
		}
		
		cursor.close();
		db.close();
    	return StudyInfo;
    	
    }
	
	
	/**Author: Anshul
	/** 
	 * This method updates the studentwebmail table with the new webmail set in
	 * by the user in the preferences menu
	 * 
	 * @return void . This method is more for setting the webmail url rather
	 *         than returning anything.
	 */
	
	public void updateWebmail(ContentValues values) {
		SQLiteDatabase db = openConnection();

		db.update("StudentWebmail", values, null, null);
		db.close();
	}
	
	/**Author: Anshul
	 * This will delete all courses that the user is enrolled in. 
	 * It would be called from the preferences screen.
	 * */
	public void deleteAllCourses(){
		
		SQLiteDatabase db = openConnection();

		db.delete("Courses", null, null);

		db.close();
	}

}